package org.peterf.foxish.net;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.peterf.foxish.R;
import org.peterf.foxish.util.EngineException;

public class NetUtil {

    public static final String UTF_8 = "UTF-8";

    public static Map<String, String> decode(String str) {
        return decode(str, UTF_8);
    }

    public static Map<String, String> decode(String str, String decode) {
        String[] kvs = str.split("&");
        Map<String, String> ret = new HashMap<String, String>();
        for (String kv : kvs) {
            String[] pair = kv.split("=");
            if (pair.length != 2) {
                throw new EngineException(R.string.foxish_err_invalid_decoding);
            }
            try {
                String value = URLDecoder.decode(pair[1], decode);
                ret.put(pair[0], value);
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        }
        return ret;
    }

    public static String encode(Map<String, String> map) {
        return encode(map, UTF_8);
    }

    public static String encode(Map<String, String> map, String encode) {
        StringBuilder builder = new StringBuilder();
        Iterator<Entry<String, String>> iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<String, String> pair = iter.next();
            builder.append(pair.getKey()).append("=");
            try {
                builder.append(URLEncoder.encode(pair.getValue(), encode));
            } catch (UnsupportedEncodingException e) {
                return null;
            }
            if (iter.hasNext()) {
                builder.append("&");
            }
        }
        return builder.toString();
    }

}
